typescript의 non-null assertion은 컴파일시에 사라진다

ChatGPT 4o Answer


⚠️ Using TypeScript's Non-Null Assertion Operator (!) Safely

🧠 What Is the Non-Null Assertion Operator?

In TypeScript, the ! operator can be placed after an expression to tell the compiler:

“I know this value is not null or undefined — trust me.”

Example:

const element = document.getElementById('header')!;

This bypasses the compiler’s type checks, assuming element is always present.


🚨 Why It Can Be Dangerous


✅ Best Practice: Validate First, Assert Last

Instead of:

const data = fetchDataById(id)!;

Use:

if (!id) {
  throw new Error('Missing id');
}
const data = await fetchDataById(id);
if (!data) {
  throw new Error('Data not found');
}

Or return structured results:

if (!id) return { success: false, reason: 'INVALID_ID' };
const data = await repo.find(id);
if (!data) return { success: false, reason: 'NOT_FOUND' };

🧾 Summary

❌ Avoid ✅ Prefer
Blindly using ! Explicit null/undefined checks
Trusting unsafe input Defensive programming
Relying on assumptions Handling edge cases gracefully

Rule of thumb: If you're reaching for !, ask yourself: "What if I'm wrong?"

Would you like a Markdown version of this for internal documentation or onboarding?